<template>
    <div class="title">{{ props.options.name }}</div>
    <div ref="chartRef" :class="props.className" :style="{ height: props.height, width: props.width }"></div>
</template>

<script setup>
import * as echarts from "echarts";
import "echarts-wordcloud";
const props = defineProps({
    // 自定义组件的类名
    className: {
        type: String,
        default: "chart",
    },
    /** 主题 */
    theme: {
        type: String,
        default: "light",
    },
    // 图表容器的宽度
    width: {
        type: String,
        default: "100%",
    },
    // 图表容器的高度
    height: {
        type: String,
        default: "100%",
    },
    // 图表参数
    options: {
        type: Object,
        default: undefined,
    },
});
const chartRef = ref(null);
let chart = null;
watch(
    () => props.options,
    (options) => {
        if (options) {
            nextTick(() => {
                if (chart) {
                    chart.setOption(options, true);
                }
            });
        }
    },
    {
        deep: true,
    }
);
const emits = defineEmits(["callbackFun"]);
onMounted(() => {
    // 设置异步，不然图例一开始的宽度不正确。
    nextTick(() => {
        initChart();
    });
});
const initChart = () => {
    // 初始化echart
    const chartRefWrap = unref(chartRef);
    if (chartRefWrap) {
        chart = echarts.init(chartRefWrap, props.theme);
        // 若图表需要点击事件做些其他功能，在初始化示例时注册图表的点击事件
        // if (props.isClick) {
        chart.on("click", (params) => {
            emits("callbackFun", params);
        });
        // }
        chart.setOption(props.options, true);
        chart.on("click", (params) => { });
        window.addEventListener("resize", chartsResize);
    }
};
onActivated(() => {
    // 防止keep-alive之后图表变形
    if (chart) {
        nextTick(() => {
            chart.resize();
        });
    }
});

const chartsResize = () => {
    chart && chart.resize();
};

onBeforeUnmount(() => {
    window.removeEventListener("resize", chartsResize);
    chart = null;
});
</script>

<style lang="scss" scoped>
.title{
    padding: 24px 0 0 24px;
}
</style>